package com.walnut.lom_system.common.securtiy;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.json.JSONUtil;
import com.walnut.lom_system.common.lang.ResultInfo;
import com.walnut.lom_system.common.util.JwtUtil;
import com.walnut.lom_system.common.util.ResultInfoUtil;
import com.walnut.lom_system.domain.entity.UserLoginInfo;
import com.walnut.lom_system.mapper.UserLoginInfoMapper;
import com.walnut.lom_system.service.UserLoginInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;

/**
 * @author walnut
 * @version 1.0
 * @date 2021/11/7 10:00 下午
 */
@Component
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserLoginInfoMapper loginInfoMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        //生成jwt，放置到请求头
        String name = authentication.getName();

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("sid",name);

        List<UserLoginInfo> userLoginInfos = loginInfoMapper.selectByMap(map);
        UserLoginInfo userLoginInfo = userLoginInfos.get(0);
        Long id = userLoginInfo.getId();

        String jwt = JwtUtil.sign(userLoginInfo.getId(), name);

        httpServletResponse.setHeader(JwtUtil.getHeader(), jwt);

        ResultInfo<Object> objectResultInfo = ResultInfoUtil.buildSuccess(id);

        outputStream.write(JSONUtil.toJsonStr(objectResultInfo).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}

